<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 *
 * 创建时间：2021-10-09 09:16:17
 *
 * 项目：/levmodules  -  $  - AdminModulesController.php
 *
 * 作者：{{AUTO GENERATE}}
 */

//此文件使用程序自动生成，下次生成时【不会】覆盖。
//在这里可以补充、完善你的程序逻辑

namespace modules\levmodules\controllers;

use Lev;
use lev\base\Assetsv;
use lev\base\Viewv;
use lev\helpers\cacheFileHelpers;
use lev\helpers\ModulesHelper;
use lev\helpers\UrlHelper;
use lev\widgets\adminModulesNav\adminModulesNav;
use modules\levmodules\controllers\_gen\BaseAdminModules;
use modules\levmodules\helpers\levmodulesSetHelper;
use modules\levmodules\helpers\zipHelper;
use modules\levmodules\helpers\zipUploadServerHelper;
use modules\levmodules\table\form\Form_lev_modules\Form_lev_modules;
use modules\levmodules\table\lev_modules\levModulesModelHelper;
use modules\levmodules\table\levmodules_merge\levmodulesMergeModelHelper;

!defined('INLEV') && exit('Access Denied LEV');

Assetsv::animateCss();

class AdminModulesController extends BaseAdminModules
{

    public static $tmpPath = 'admin-modules';
    public static $trash   = false;//是否允许删除数据

    public static $addurl = true;//是否显示创建数据按钮

    public static $srhtitle    = '模块名称、标识符';//模糊搜索字段名称
    public static $srhkeyWhere = "name LIKE '%{srhkey}%' OR identifier LIKE '%{srhkey}%'";//模糊搜索sql语句 例：name LIKE '%{srhkey}%'

    public static $limit = 200;//每页显示多少条
    public static $order = ['status ASC, displayorder ASC, versiontime DESC'];//排序

    public static function col_typeid() {
        return [
            0 => '三方模块',
            8 => '官方模块',
            9 => '基础模块',
        ];
    }

    public static function actionIndex()
    {
        return parent::actionIndex(); // TODO: Change the autogenerated stub
    }

    /**
     * 合并压缩，将多个模块压缩在一起
     */
    public static function actionMergeZip()
    {
        $_checkHideT = intval(Lev::GPv('checkHideT'));
        $unzip = Lev::GPv('unzip') ? 1 : 0;
        $mainIden = Lev::stripTags(Lev::GPv('mainIden'));
        $ids = Lev::stripTags(Lev::GPv('ids'));
        $changeAdminEnter = Lev::stripTags(Lev::GPv('changeAdminEnter'));
        $mergeDesc = Lev::stripTags(Lev::GPv('mergeDesc'));

        $checkHideT = $_checkHideT === 1 ? 1 : 0;
        $devZip = $_checkHideT === 2 ? true : false;

        if (count($ids) <2) {
            Lev::showMessages(Lev::responseMsg(-111, '至少选择两个模块'));
        }
        $muds = ModulesHelper::findAll('id IN ('.implode(',', $ids).')', 'identifier');
        if (count($muds) <2) {
            Lev::showMessages(Lev::responseMsg(-112, '存在不合法模块'));
        }
        $mainInfo = ModulesHelper::getModuleInfo($mainIden);
        if (empty($mainInfo)) {
            Lev::showMessages(Lev::responseMsg(-122, '主模块不存在'));
        }
        if (!empty($muds[$mainIden]['classdir'])) {
            Lev::showMessages(Lev::responseMsg(-132, '子模块不能作为主模块'));
        }
        $idens[$mainIden][$mainIden] = $mainInfo;
        $idensOnly[] = $mainIden;
        unset($muds[$mainIden]);
        foreach ($muds as $mud) {
            if ($mud['classdir'] && !isset($idens[$mud['classdir']])) {
                $idens[$mud['classdir']][$mud['classdir']] = ModulesHelper::getModuleInfo($mud['classdir']);
            }
            $idens[$mud['classdir']][$mud['identifier']] = $mud;
            $idensOnly[] = $mud['identifier'];
        }
        if ($devZip) {
            zipHelper::setDevZip();
        }
        $resMsg = zipHelper::doZipMerges($mainIden, $idens, $checkHideT, $unzip, $changeAdminEnter);
        $resMsg['unzip'] = $unzip;
        if ($unzip) {
            levmodulesMergeModelHelper::insert([
                'descs' => $mergeDesc,
                'mainiden' => $mainIden,
                'hidelevs' => $_checkHideT,
                'idens' => json_encode($idensOnly),
                'adminiden' => $changeAdminEnter['id'],
                'adminroute' => $changeAdminEnter['r'],
                'adminclassify' => $changeAdminEnter['classify'],
                'addtime' => Lev::$app['timestamp'],
            ]);
        }
        Lev::showMessages($resMsg);
    }

    /**
     * 批量上传压缩包到服务器
     *
     * @see FormUploadZipsController::actionApi() 服务器接收方法
     */
    public static function actionAjaxBatchZipUpload() {//Lev::debug();

        $serverid = Lev::stripTags(Lev::GPv('serverid'));
        $zipid = floatval(Lev::GPv('zipid'));
        $mudInfo = ModulesHelper::findOne(['id'=>$zipid]);

        if ($serverid === 'levstore') {
            Lev::showMessages(zipUploadServerHelper::uploadStore($mudInfo['identifier']));
        }else {
            echo json_encode(zipUploadServerHelper::upload($serverid, $mudInfo));
        }
    }

    /**
     * 批量执行已配置 压缩
     * 使用 js ajax 循环调用此接口
     */
    public static function actionAjaxBatchZip() {
        $zipid = floatval(Lev::GPv('zipid'));
        $mudInfo = ModulesHelper::findOne(['id'=>$zipid]);
        $iden = $mudInfo['identifier'];
        $zipConfig = levModulesModelHelper::cacheZipConfig($iden);
        if (empty($zipConfig)) {
            $zipMsg = Lev::responseMsg(-44, '<tips>抱歉，请手动执行一次压缩</tips>');
        }else {
            if (!empty($zipConfig['export'])) {
                Form_lev_modules::doExport($zipid, false, $mudInfo);
                SettingsController::doExport(false, $iden);
            }
            zipHelper::$changeFiles['LevVersion'] = $zipConfig['LevVersion'] ?: levmodulesSetHelper::LevVersion();
            $zipMsg = zipHelper::doZip($iden, $zipConfig['classdir'], $zipConfig['addLev'], $zipConfig['unFiles'], $zipConfig['replaces'], $zipConfig['updateDesc']);
        }
        echo json_encode($zipMsg);
    }

    public static function showColumns() {
        return array(
            //'id'           => array('order' => null, 'name' => 'Id', 'thattr' => 'wd30 nowrap'),

            //'typeid'       => array('order' => null, 'name' => '分类', 'thattr' => 'wd30 nowrap'),

            'displayorder' => array('order' => null, 'name' => '排序', 'thattr' => 'wd30 nowrap', 'merge' => ['id']),

            'identifier'   => array('order' => null, 'name' => '唯一标识', 'thattr' => 'wd30 nowrap'),

            'name'         => array('order' => null, 'name' => '模块名称', 'thattr' => 'wd30 nowrap', 'merge' => ['copyright']),

            //'classdir'     => array('order' => null, 'name' => 'Classdir', 'thattr' => 'wd30 nowrap'),

            '_descs'        => array('order' => null, 'name' => '简短描述', 'thattr' => '', 'merge' => ['descs']),

            //'descs'        => array('order' => null, 'name' => '简短描述', 'thattr' => ''),

            //'copyright'    => array('order' => null, 'name' => '版权', 'thattr' => 'wd30 nowrap'),

            'settings___price' => array('order' => null, 'name' => '商城价格(元)', 'thattr' => 'wd30 nowrap', 'merge' => []),

            'version'      => array('order' => null, 'name' => '版本号', 'thattr' => 'wd30 nowrap', 'merge' => ['versiontime']),

            //'versiontime'  => array('order' => null, 'name' => '版本时间号', 'thattr' => 'wd30 nowrap'),

            //'settings'     => array('order' => null, 'name' => '通用设置', 'thattr' => 'wd30 nowrap'),

            'status'       => array('order' => null, 'name' => '状态', 'thattr' => 'wd30 nowrap'),

            'uptime'       => array('order' => 1, 'name' => '更新时间', 'thattr' => 'wd30 nowrap'),

            '##btns'       => array('order' => null, 'name' => '功能设计', 'thattr' => 'wd30 nowrap'),

            //'addtime'      => array('order' => null, 'name' => '添加时间', 'thattr' => 'wd30 nowrap'),

        );
    }

    public static function setColumnShowtype()
    {
        //return parent::setColumnShowtype(); // TODO: Change the autogenerated stub
        return [
            'showtype' => [
                'input_version' => 1,
                'input_name' => ['width'=>130],
                'input_copyright' => [],
                'input_descs' => ['width'=>530],

                'srhkey_classdir' => ['or'=>['identifier']],
                'srhkey_identifier' => ['or'=>'classdir'],
                //'time_versiontime' => 1,
            ],
        ];
    }

    public static function myselfBtns($v) {
        return [
            [
                'name' => '<b title="导出表数据、设置项"><svg class="icon"><use xlink:href="#fa-login"></use></svg></b>',
                'link' => Lev::toReRoute(['modules/export', 'opid'=>$v['id']]),
                'attr' => 'color-yellow" target="_blank',
            ],
            [
                'name' => '<b title="压缩模块"><svg class="icon"><use xlink:href="#fa-txb"></use></svg></b>',
                'link' => UrlHelper::zip($v['identifier'], $v['id']),
                'attr' => 'color-lightblue" target="_blank',
            ],
            [
                'name' => '<b title="上传到模块商店"><svg class="icon"><use xlink:href="#fa-cloud"></use></svg></b>',
                'link' => UrlHelper::zipUploadStore($v['identifier'], $v['id']),
                'attr' => 'color-orange" target="_blank',
            ],
        ];
    }
    public static function myselfBtns2($v) {
        return [
            [
                'name' => '<b title="增加模块配置项"><svg class="icon"><use xlink:href="#fa-websj"></use></svg></b>',
                'link' => Lev::toReRoute(['settings', 'iden'=>$v['identifier'], 'id'=>'levmodules']),
                'attr' => 'color-yellow" target="_blank',
            ],
            [
                'name' => '<b title="创建表单"><svg class="icon"><use xlink:href="#fa-zh"></use></svg></b>',
                'link' => Lev::toReRoute(['settings', 'isForm'=>1, 'iden'=>$v['identifier'], 'id'=>'levmodules', 'mudid'=>$v['id']]),
                'attr' => 'color-black" target="_blank',
            ],
        ];
    }

    public static function formatListsv($sv, $lists)
    {
        $v = $sv;
        $s = Lev::getSettings($sv['settings']);
        $sv = parent::formatListsv($sv, $lists); // TODO: Change the autogenerated stub
        $sv['_descs'] = '<div class="data-xtable"><div class="mud-navb buttons-row scale6 transl">'
            .ModulesHelper::getAdminNavHtms($sv).'</div></div>
                        <div class="data-xtable"><div class="mud-navb buttons-row scale6 transl">'
            .ModulesHelper::getPageNavHtms($sv).'</div></div>';

        //$idenHref = Lev::toReRoute(['superman/modules', 'id' => $v['classdir'] ?: $v['identifier']]);
        $cpm = empty($v['classdir']) ? ['identifier'=>$v['identifier']] : ['classdir'=>$v['classdir']];
        $idenHref = Lev::toCurrent($cpm);
        if ($v['classdir']) {
            $sv['identifier'] = '<a href="'.$idenHref.'" class="Idenv_'.$v['identifier'].'">'.$v['classdir'].'</a><p>'.$v['identifier'].'</p>';
        }else {
            $sv['identifier'] = ($v['identifier'] == APPVIDEN ? '<absx>主体</absx>' : '') . '
<a href="' . $idenHref . '" class="Idenv_'.$v['identifier'].'">' . $v['identifier'] . '</a>';
        }
        //$sv['name'] .= '<p class="date transl" title="版权">'.$v['copyright'].'</p>';
        //$sv['version'].= '<p class="date transl" title="'.date('Ymd.His', $v['versiontime']).'">'.Lev::asRealTime($v['versiontime'], '新装').'更新</p>';
        $sv['##btns'] = '<div style="height:20px;min-width:40px;">'.adminModulesNav::btnsrowHtm(static::myselfBtns($v), 'scale6 transl').'</div>';
        $sv['##btns'].= adminModulesNav::btnsrowHtm(static::myselfBtns2($v), 'scale6 transl wd80');

        $_price = $s['_price'];
        $_upprice = $s['_upprice'];
        $sv['settings___price'] = '<input type="text" name="settings___price" class="wd80 set-field setField" value="'.$_price.'" opid="'.$v['id'].'" autocomplete="off">';
        $sv['settings___price'].= '<p><input title="升级价格" type="text" name="settings___upprice" class="wd80 set-field setField" value="'.$_upprice.'" opid="'.$v['id'].'" autocomplete="off"></p>';

        ($newzip = zipHelper::optNewZipCache($v['identifier'])) &&
        $sv['copyright'] = '<tips title="'.Lev::stripTags(print_r($newzip, true)).'">新ZIP未上传：'.Lev::asRealTime($newzip['lastEditTime']).'</tips>';

        return $sv;
    }

    public static function redirct($columnKey, $sv)
    {
        //return parent::redirct($columnKey, $sv); // TODO: Change the autogenerated stub
        switch ($columnKey) {
            case 'name': $a = '<a _bk=1 target=_blank class="date inblk" href="'.Lev::toReRoute(['/', 'id'=>$sv['identifier']]).'"><svg class="icon color-black"><use xlink:href="#fa-huoj"></use></svg></a>'; break;
            default: $a = ''; break;
        }
        return $a;
    }

    public static function optButtons($sv)
    {
        //return parent::optButtons($sv); // TODO: Change the autogenerated stub
        $btns = [
            ['name'=>'更新', 'r'=>'superman/update-module', 'color'=>ModulesHelper::checkNewConfig($sv) ? 'red' : 'gray'],
            ['name'=>'安装', 'r'=>'superman/install-module', 'color'=>'black'],
            ['name'=>'卸载', 'r'=>'superman/uninstall-module', 'color'=>'gray'],
        ];
        $htms = '<div class="wd30 nowrap flex-box">';
        foreach ($btns as $v) {
            $htms .= '<a class="button button-fill color-' . $v['color'] . ' wd30 wdmin" href="' . Lev::toReRoute([$v['r'], 'id' => APPVIDEN, 'iden' => $sv['identifier'], 'classdir' => $sv['classdir']]) . '">'.$v['name'].'</a>';
        }
        return $htms.'</div>&nbsp;&nbsp;';
    }

    public static function footerBtns($btns = [])
    {
        $btns = parent::footerBtns($btns); // TODO: Change the autogenerated stub
        $btns[] = [
            'name' => '<svg class="icon"><use xlink:href="#fa-up"></use></svg> FTP上传设置',
            'link' => UrlHelper::ftpsettings(),
            'attr' => 'color-orange" target="_blank',
        ];
        return $btns;
    }

    public static function cardFooterButtons($btns = [])
    {
        //return parent::cardFooterButtons($btns); // TODO: Change the autogenerated stub
        return '<tips class="gray inblk scale8">自定义cardFooterButtons</tips>';
    }

    public static function headerHtm()
    { // TODO: Change the autogenerated stub
        $mergeid = floatval(Lev::GPv('mergeid'));

        $mereIdens = $meInfo = [];
        if ($mergeid >0) {
            $meInfo = levmodulesMergeModelHelper::staticInfo($mergeid);
            $mereIdens = json_decode($meInfo['idens'], true);
        }
        return Viewv::renderPartial(static::$tmpPath . '/myself/header_htm', [
            'servers' => levmodulesSetHelper::serversOpen(),
            'mergeIdens' => $mereIdens,
            'meInfo' => $meInfo,
        ]);
    }

    public static function footerHtm()
    {
        //return parent::footerHtm(); // TODO: Change the autogenerated stub
        return '<tips class="gray inblk scale8">自定义footerHtm</tips>';
    }

}